/*
 * Copyright (c) 2023.
 *
 * 作者：bmy
 * 邮箱：2271608011@qq.com
 * gitee：https://gitee.com/bmycode
 * github：https://github.com/helpcode
 *
 */

import { BaseDirectory, createDir, exists, writeTextFile, readTextFile } from "@tauri-apps/plugin-fs";
import { homeDir } from '@tauri-apps/api/path';

export type value = 1 | 0;
export type themeValueType = 'light' | 'dark';


export interface DbConfig {
  JsonType: value;
  needProperty: value;
  needPropertyValue: value;
  nullAlias: string;

  autoSave: value;
  savePath: string;
  saveFileName: string

  theme: themeValueType,
  autoThemeSystem: value;
  autoLoginStart: value;

  lineNumbers: 'on' | 'off';
  minimap: value;
  autoClipboard: value;
}

class JsonDatabase {

  // 文件夹名称
  DirectoryName: string = ".jsontoclass"

  // 保存配置的json文件名
  JsonFileName: string = "db.json"

  // 文件夹 + json 文件 .jsontoclass/db.json
  DbFullPath: string = `${this.DirectoryName}/${this.JsonFileName}`

  // UI框架限制RadioGroup这类UI组件的 items 中 value 和 bind:value 必须为 string，所以这里
  // 存储 设置项 不使用 boolean，组件内 会对 number 0 进行 String
  DataBaseConfig: DbConfig = {
    JsonType         : 0,
    needProperty     : 0,
    needPropertyValue: 0,
    nullAlias        : "string",

    autoSave    : 0,
    savePath    : "",
    saveFileName: "",

    theme          : "light",
    autoThemeSystem: 0,
    autoLoginStart : 0,

    lineNumbers: "off",
    minimap: 0,
    autoClipboard: 0
  }

  /**
   * 创建json数据库
   * @constructor
   */
  public async CreatedJsonDataBase() {
    let rootPath = await homeDir();
    let fullPath: string = `${ await homeDir() }/${ this.DbFullPath }`
    if (!await exists(`${ rootPath }/${ this.DirectoryName }`)) {
      await createDir(this.DirectoryName, { dir: BaseDirectory.Home })
      if (!await exists(fullPath)) {
        await this.writeJson(this.DataBaseConfig);
      }
    }
  }

  public async readJson(): Promise<DbConfig> {
    await this.CreatedJsonDataBase();
    const res = await readTextFile(this.DbFullPath, { dir: BaseDirectory.Home });
    return JSON.parse(res);
  }

  public async writeJson(str: DbConfig) {
    await writeTextFile(this.DbFullPath, JSON.stringify(str), { dir: BaseDirectory.Home });
  }
}

export default new JsonDatabase
